package com.lagou.homework;

import java.sql.*;

public class JDBCUtils {

    // 1.设置常量，驱动连接用
    public static final String DRIVENAME = "com.mysql.jdbc.Driver";
    public static final String URL = "jdbc:mysql://localhost:3306/2-1work?characterEncoding=UTF-8";
    public static final String USERNAME =  "root";
    public static final String PASSWORD = "123456";

    // 2.静态代码块
    static {

        try {
            Class.forName(DRIVENAME);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 3.获取连接对象
    public static Connection getConnection() {

        Connection connection = null;
        try {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 4.关闭资源
    public static void close(Connection connection, Statement statement) {

        if(null != statement && null != connection) {
            try {
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet) {

        if(null != statement && null != connection && null != resultSet) {
            try {
                resultSet.close();
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
